import { useState, useEffect } from 'react'
import { Form, message } from 'antd'
import { useRecoilValue } from 'recoil'
import { useNavigate } from 'react-router-dom'
import moment from 'moment'
import { IWardManage, pageType, ITableParams, IFilterParams, IManage, TableDataType, topConfigType } from '../type'
import {
  getWard,
  getYearSelect,
  getWordSelector,
  getWordCatalogue,
  addAdmin,
  editAdmin,
  deleteAdmin,
  exportTableData,
} from '../service/service'
import { isNullData } from '@/utils'
import { dictValuesSelector } from '@/store/dicts'
import { userInfo } from '@/store/userInfo'
import { exportData } from '@/utils/index'

export default (): IWardManage => {
  const pushRouter = useNavigate()
  const user = useRecoilValue(userInfo)
  console.log('useruser🦢🦢', user)
  // 字典
  const dictValuesSelectorValues = useRecoilValue(dictValuesSelector)

  // 筛选form
  const [filterForm] = Form.useForm()
  // 弹框form
  const [modalForm] = Form.useForm()

  // 展示管理员弹窗
  const [showManage, setShowMange] = useState<boolean>(false)
  // 新增还是编辑
  const [addAndEdit, setAddAndEdit] = useState<boolean>(false)

  // 分页信息
  const [pageParams, setPageParams] = useState<pageType>({
    totalCount: 0,
    pageIndex: 1,
    pageSize: 10,
  })

  // 顶部下拉，搜索框值存储
  const [topConfigValue, setTopConfigValue] = useState({
    wordSelectValue: [],
    loginYearValue: '',
    inputValue: '',
  })

  // 存储的表格数据
  const [tableData, setTableData] = useState<TableDataType[]>([])

  // 存储的年份下拉框数据
  const [yearDatas, setYearDatas] = useState([])

  // 顶部病区二级联动数据
  const [topWordSelectCascader, setTopWordSelectCascader] = useState([])

  // 弹框目录的三级联动数据
  const [modalLinkageData, setModalLinkageData] = useState([])

  // 点击编辑存储的状态
  const [editData, setEditData] = useState<any>({})

  // 更换页码
  const handleChangePage = async (page: number, pageSize?: number) => {
    await setPageParams((v) => ({
      ...v,
      pageIndex: page,
      pageSize: pageSize || pageParams.pageSize,
    }))
  }

  // 获取选择病区的下拉框数据
  const getWardSelectValue = (value: any) => {
    // 处理点击清除按钮之后数据为空的问题
    if (!value) {
      setTopConfigValue({ ...topConfigValue, wordSelectValue: [] })
    } else {
      setTopConfigValue({ ...topConfigValue, wordSelectValue: value })
    }
  }

  // 获取登录次数下拉框数据
  const getLoginTimeValue = (value: string) => {
    setTopConfigValue({ ...topConfigValue, loginYearValue: value })
  }

  // 获取姓名手机号 Input 输入内容
  const getInputValue = (e: any) => {
    const { value } = e.target
    setTopConfigValue({ ...topConfigValue, inputValue: value })
  }

  // 点击新增病区管理员打开弹框
  const clickAddWordAdminOpenModal = () => {
    setShowMange(true)
    setAddAndEdit(true) // 变成新增
  }
  // 点击编辑打开管理员弹框
  const clickEditWordAdminModal = (record: any) => {
    console.log('🦢🦢', record)
    setEditData(record)
    record.typeIds = record.typeIds?.map((item: any) => item.toString()) // 三级转换成字符串回显
    setShowMange(true)
    setAddAndEdit(false) // 变成编辑
    modalForm.setFieldsValue({ ...record, inpatientWardId: record.typeIds })
  }
  // 弹框完全关闭
  const handelModal = () => {
    modalForm.resetFields()
  }

  // 转换成文字
  const findLabels = (data: any, values: any) => {
    const labels: any = []
    function traverse(node: any, targetValues: any) {
      if (targetValues.includes(node.value)) {
        labels.push(node.label)
      }
      if (node.children) {
        node.children.forEach((child: any) => traverse(child, targetValues))
      }
    }
    data.forEach((node: any) => traverse(node, values))
    return labels.join('/')
  }
  // 点击查看跳转到查看页面
  const clickExamine = (record: any) => {
    record.typeIds = record.typeIds?.map((item: any) => item.toString())
    record.typeIds = findLabels(modalLinkageData, record.typeIds)
    pushRouter('/user-admin-hospital/wardManage-examine-hospital', { state: record })
  }

  // 获取病区管理员信息表格数据
  const getTableList = async () => {
    const params = {
      pageSize: pageParams.pageSize,
      pageIndex: pageParams.pageIndex,
      search: {
        oneType: topConfigValue.wordSelectValue[0],
        twoType: topConfigValue.wordSelectValue[1],
        loginTimes: topConfigValue.loginYearValue || '',
        queryContent: topConfigValue.inputValue || '',
      },
    }
    const res = await getWard(params)
    if (isNullData(res)) {
      setTableData(res.data.items)
      setPageParams({ ...pageParams, totalCount: res.data.totalCount }) // 改页面数量
    }
  }

  // 确认删除
  const affifmDelete = async (record: any) => {
    const res = await deleteAdmin({ id: record.id })
    // 此处判断，该账号是有病区上报任务的就阻止
    if (isNullData(res) && res.data.success === 1) {
      message.info(res.data.message)
    } else {
      message.success('删除成功')
      getTableList()
    }
  }

  // 输入框回车事件
  const inputEnter = () => {
    getTableList()
  }

  const beginGet = async () => {
    await getTableList() // 表格数据
  }

  // 弹框确认
  const modalFinish = async (value: any) => {
    if (addAndEdit) {
      value.inpatientWardId = value.inpatientWardId[value.inpatientWardId.length - 1]
      const res = await addAdmin(value)
      if (res.success === 200) {
        message.success('新增管理员成功')
        setShowMange(false)
      } else {
        message.info(res.message)
        setShowMange(true)
      }
    } else {
      value.id = editData.id
      value.inpatientWardId = value.inpatientWardId[value.inpatientWardId.length - 1]
      const res = await editAdmin(value)
      if (res && res.success === 200) {
        message.success('编辑成功')
        setShowMange(false)
      }
    }

    getTableList()
  }

  // 获取年
  const getYearData = async () => {
    const res = await getYearSelect()
    const yearSelectData = res.data.reduce((acc: any, cur: any) => {
      acc.push({ value: cur, lable: cur })
      return acc
    }, [])
    setYearDatas(yearSelectData)
  }

  // 递归函数，将原始数据转换为 Cascader 数据结构
  const transformData = (data: any) =>
    data?.map((item: any) => {
      const { id, code, fatherId, unit, children } = item
      // const { unit, children } = item
      const cascaderItem = {
        value: unit,
        label: unit,
        children: transformData(children),
      }
      return cascaderItem
    })
  // 获取顶部下拉框数据结构
  const getWordSelectorValues = async () => {
    const res = await getWordSelector()
    const filterCascader = transformData(res.data)
    setTopWordSelectCascader(filterCascader)
  }

  // 递归函数，将原始数据转换为 Cascader 数据结构
  const transformDataCatalogue = (items: any) =>
    items.map((item: any) => {
      const dis = item.type === '20' && item.endemicAreaVos.length === 0
      const cascaderItem: any = {
        label: item.unit,
        value: item.id.toString(),
        disabled: dis,
      }
      if (item.endemicAreaVos.length > 0) {
        cascaderItem.children = transformDataCatalogue(item.endemicAreaVos)
      }
      return cascaderItem
    })
  // 获取目录
  const getWordCatalogueData = async () => {
    const params = {
      hospitalCode: user.hospitalCode,
    }
    const res = await getWordCatalogue(params)
    if (isNullData(res)) {
      console.log('🦢🦢', res.data.endemicAreaVos)
      const LinkageData = transformDataCatalogue(res.data.endemicAreaVos)
      // setModalLinkageData(setDisabledForOptions(LinkageData))
      setModalLinkageData(LinkageData)
      console.log('🦢🦢', LinkageData)
    }
  }

  // 导出事件
  const exportDataClick = async () => {
    // console.log('🦢🦢点击了导出')
    const params = {
      oneType: topConfigValue.wordSelectValue[0] || '',
      twoType: topConfigValue.wordSelectValue[1] || '',
      loginTimes: topConfigValue.loginYearValue || '',
      queryContent: topConfigValue.inputValue || '',
    }
    const res = await exportTableData(params)
    const title = '病区管理员信息'
    exportData(res, title, 'xlsx')
  }

  // 弹框取消事件
  const clearModal = () => {
    setShowMange(false)
  }

  // 控制新增病区管理员按钮显示。。。日期为 1-01 日到 3-31日可以显示新增按钮
  const filterAddWardAdminButton = () => {
    const currentDate = moment()
    const momentYear = moment().year()
    const startDate = moment().year(momentYear).startOf('year') // 获取一月初
    const endDate = moment().year(momentYear).month(2).endOf('month') // 获取三月末
    const isWithinRange = currentDate.isBetween(startDate, endDate, null, '[]')
    return isWithinRange
  }

  useEffect(() => {
    beginGet()
    getYearData()
    getWordSelectorValues()
    getWordCatalogueData()
  }, [])

  // 顶部配置改变时触发重新搜索表格数据
  useEffect(() => {
    beginGet()
  }, [topConfigValue.wordSelectValue, topConfigValue.loginYearValue, pageParams.pageIndex, pageParams.pageSize])

  // Form 表单配置
  const filterParams: IFilterParams = {
    filterForm,
    clearModal,
  }

  // 表格配置
  const tableParams: ITableParams = {
    handleChangePage,
    pageParams,
    setShowMange,
    tableData,
    affifmDelete,
    clickExamine,
  }

  // 弹框配置
  const manageParams: IManage = {
    showManage,
    setShowMange,
    clickAddWordAdminOpenModal,
    clickEditWordAdminModal,
    handelModal,
    modalLinkageData,
    modalForm,
    modalFinish,
    filterAddWardAdminButton,
  }

  // 顶部下拉框和输入框配置
  const topConfig: topConfigType = {
    getWardSelectValue,
    getLoginTimeValue,
    getInputValue,
    inputEnter,
    yearDatas,
    addAndEdit,
    topWordSelectCascader,
    exportDataClick,
  }

  return {
    tableParams,
    filterParams,
    manageParams,
    topConfig,
  }
}
